<template>
  <div class="jq-table h-full flex-col">
    <div class="packageCardcontainer">
      <template v-for="boxContent in contentList" :key="boxContent?.title">
        <PackageCard class="card" :boxContent="boxContent" />
      </template>
    </div>
    <SearchForm
      @handle-reset-form-datas="handleResetFormDatas"
      :searchForm="searchForm"
      @handle-search="handleSearch"
      @chanFormValue="chanFormValue"
    />
    <div class="page-card h-full" v-loading="loading">
      <JqTable
        :tableColumn="tableColumn"
        :tableButtons="tableButtons"
        :itemsButtons="itemsButtons"
        :data="tableData"
        :page="page"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      >
      
      <template #statusText>
          <el-table-column
            show-overflow-tooltip
            :min-width="80"
            prop="statusText"
            label="状态"
            fit="true"
            show-header="true"
            align="left"
          >
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span :class="scope.row.status === 1 ? 'point1' : 'point2'"></span>
                <span>{{ scope.row['statusText'] }}</span>
              </div>
            </template>
          </el-table-column>
      </template>
      </JqTable>
      <!-- <AddOrUpdateForStaff 
      ref="addOrUpdateRef" 
      :visible='visible' 
      :dialogDatas="dialogDatas" 
      @clear-form-datas="clearFormDatas"
      @on-cancel="onCancel" 
      @on-confirm="onConfirm" /> -->
      <AddOrUpdateForStaff
        v-if="showDialog"
        v-model:dialogVisible="showDialog"
        ref="addOrUpdateRef"
        :dialogDatas="dialogDatas"
        @update-list="updateList"
      />
      <resignInherit
        ref="resignInheritRef"
        :dialogDatas="dialogDatas2"
        @on-cancel="onCancel"
        @on-confirm="onConfirm"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'SystemStaff' }); //员工管理
import { reactive, ref, watch, onMounted, computed } from 'vue';
import { useTable } from '@/hooks/useTable';
import {
  adminUserSetResignRequest,
  getQueryAdmin,
  getAdminBanner,
  getadminUserSave,
  getInfoRequest,
  adminUserEditRequest,
  adminUserResignRequest,
  adminUserUpdateStatusRequest,
  exportRequest
} from '@/api/system/adminUser/index'; //api
import { JqTable } from '@/components/Table/index';
import AddOrUpdateForStaff from '@/views/system/staff/components/add-or-update/index.vue';
import resignInherit from '@/views/system/staff/components/resignInherit/index.vue';
import { PackageCard } from '@/components/PackageCard/index';
import { useRoute, useRouter } from 'vue-router';
import { enumListRequest } from '@/api/common/index';
const router = useRouter();
import { useRouteStore } from '@/store';
// import { useUserStore } from '@/store';
// const userStore = useUserStore();
const routeStore = useRouteStore();
const currentMenudatas = computed(() => routeStore.currentMenudatas); //路由btn

import {
  orgOptionsRequest,
  roleOptionsRequest,
  getCheckPointsOptionsRequest,
  healthDoctorOptionsRequest
} from '@/api/common'; //公共接口
const addOrUpdateRef = ref();
const resignInheritRef = ref();
let searchFormParams = reactive({});
let orgIdDatas = reactive([]);
let roleOptionsValue = reactive([]);
interface Row {
  id: number;
  status: number;
  checkPointsId: number;
  statusConfig: object;
}
let visible = ref(false); //控制弹出框关闭隐藏
// 搜索字段
let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '员工查询',
    placeholder: '请输入员工查询',
    eName: 'keyword'
  },
  {
    type: 'select',
    value: '',
    label: '归属组织',
    placeholder: '全部',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'select',
    value: '',
    label: '角色',
    options: () => {
      return roleOptionsValue;
    },
    eName: 'roleId'
  }
]);
// table列表字段
const tableColumn = reactive([
  { label: '员工姓名', prop: 'employeeName', minWidth: '80' },
  { label: '归属组织机构', prop: 'orgName', minWidth: '120' },
  { label: '创建时间', prop: 'createTime', minWidth: '170' },
  { label: '离职时间', prop: 'departTime', minWidth: '80' },
  { label: '状态', prop: 'statusText', minWidth: '80', slot: true },
  { label: '手机号', prop: 'phone', minWidth: '140' },
  { label: '是否健康顾问', prop: 'isHealthDoctor', minWidth: '120' },
  { label: '角色', prop: 'roleName', minWidth: '60' }
]);
const showDialog = ref(false);
let tableButtons = reactive([
  {
    id: 43,
    type: 'primary',
    label: '添加',
    perms: 'sys:emp:btn:create',
    onClick: () => {
      clearFormDatas();
      showDialog.value = true;
      dialogDatas = {
        title: '新增员工',
        type: 'add',
        dialogForBaseFormDatas: dialogForBaseFormDatas,
        dialogForAssistantFormDatas: dialogForAssistantFormDatas
      };
      // onAddOrUpdate(dialogDatas);
    }
  },
  {
    id: 50,
    type: '',
    label: '导出',
    perms: 'sys:emp:btn:export',
    onClick: async () => {
      const params = Object.assign({}, searchFormParams, {
        pageNum: page.page,
        pageSize: page.pageSize
      });
      const data: any = await exportRequest(params);
      window.open(data.data);
    }
  }
]);
const lizhijicheng = (data: any) => {
  //离职继承
  resignInheritRef.value.init(data);
};
// 离职继承字段
let dialogForConfigDatas = reactive([
  {
    type: 'input',
    value: '',
    label: '归属组织',
    eName: 'orgName',
    placeholder: '归属组织'
  },
  {
    type: 'select',
    value: '',
    label: '现有客户转交',
    placeholder: '请选择',
    options: () => {
      return healthDoctorOptions.value;
    },
    eName: 'orgId'
  }
]);

const onAddOrUpdate = (data?: Recordable) => {
  // addOrUpdateRef.value.handleDialog(true);
  addOrUpdateRef.value.init(data);
};
let itemsButtons = reactive([
  {
    id: 44,
    type: 'primary',
    label: '查看',
    perms: 'sys:emp:btn:view',
    // onClick: (row: any) => {
    //   setDialogDefaultDatas(row, 'check');
    // }
    onClick: (row: Row) => {
      // router.push('/myTest');
      showDialog.value = true;
      dialogDatas = {
        title: '查看',
        type: 'check',
        datas: row
      };
    }
  },
  {
    id: 45,
    type: 'primary',
    label: '编辑',
    perms: 'sys:emp:btn:edit',
    // onClick: (row: []) => {
    //   setDialogDefaultDatas(row, 'edit');
    //   // console.log('row', row);
    //   // onAddOrUpdate(row);
    // }
    onClick: (row: Row) => {
      showDialog.value = true;
      dialogDatas = {
        title: '编辑',
        type: 'edit',
        datas: row
      };
    }
  },
  // {
  //   eName: 'stop',
  //   id: 46,
  //   type: 'warning',
  //   label: '停用',
  //   onClick: async (row: any) => {
  //     await getEnableOrDisablDatas({ id: row.id,status: row.status === 1 ? 2 : 1  });
  //     getList();
  //   }
  // },
  {
    id: 46,
    eName: 'pause',
    perms: 'sys:emp:btn:status',
    statusConfig: {
      1: '启用',
      2: '停用'
      // 3:'待激活'
    },
    onClick: async (row: any) => {
      getEnableOrDisablDatas({ id: row.id, status: row.status === 1 ? 2 : 1 }).then((res) => {
        getList();
        ElMessage.success('修改成功');
      });
    }
  },
  {
    id: 47,
    type: 'primary',
    perms: 'sys:emp:btn:out',
    label: '离职',
    onClick: (row: []) => {
      onlizhi(row);
    }
  },
  {
    id: 48,
    type: 'primary',
    label: '离职继承',
    perms: 'sys:emp:btn:extends',
    onClick: (row: any) => {
      setDialogDefaultDatas2(row);
      dialogDatas2 = {
        title: '离职继承',
        type: 'lzjc',
        rowData: row,
        datas: dialogForConfigDatas
      };
      lizhijicheng(dialogDatas2);
    }
  }
]);
const setDialogDefaultDatas2 = (row: { [x: string]: string }) => {
  dialogForConfigDatas.forEach((d) => {
    d.value = row[d.eName];
  });
};
let healthDoctorOptions = ref([]); //现有客户转交（归属健康顾问下拉）
watch(
  () => dialogForConfigDatas[0].value,
  (newVal, oldVal) => {
    // debugger
    // getHealthDoctorOptions(newVal)
  },
  { deep: true }
);
// 健康顾问下拉
const getHealthDoctorOptions = async (id: any) => {
  if (id && id !== null) {
    const data: any = await healthDoctorOptionsRequest({ orgId: id });
    healthDoctorOptions.value = data.data;
  } else {
    healthDoctorOptions.value = [];
  }
};

// 顶部banner
let contentList = reactive([
  {
    title: '员工总数',
    number: '',
    bgUrl: 'Bg.png',
    iconUrl: 'Icon.png'
  },
  {
    title: '总部员工总数',
    number: '',
    bgUrl: 'Bg2.png',
    iconUrl: 'Icon2.png'
  },
  {
    title: '合作机构员工数',
    number: '',
    bgUrl: 'Bg3.png',
    iconUrl: 'Icon3.png'
  }
]);
let dialogDatas = reactive({});
let dialogDatas2 = reactive({});
const { tableData, page, loading, resetParams, getList, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: getQueryAdmin,
    params: () => searchFormParams
  });
let dialogForBaseFormDatas = reactive([
  {
    type: 'input',
    value: null,
    label: '手机号码',
    eName: 'phone',
    required: true,
    inType: 'number',
    placeholder: '请输入正确的手机号码'
  },
  {
    type: 'input',
    value: '',
    label: '员工姓名',
    eName: 'employeeName',
    required: true,
    placeholder: '请填写顾问姓名'
  },
  {
    type: 'select',
    value: '',
    label: '归属组织机构',
    required: true,
    placeholder: '请选择归属组织',
    options: () => {
      return orgIdDatas;
    },
    eName: 'orgId'
  },
  {
    type: 'select',
    value: '',
    label: '状态',
    required: true,
    placeholder: '请选择状态',
    options: () => {
      return [
        { id: 1, name: '在职启用' },
        { id: 2, name: '在职停用' },
        { id: 3, name: '离职' }
      ];
    },
    eName: 'userStatus'
  },
  {
    type: 'select',
    Ttype: 'multiple',
    value: [],
    label: '角色',
    required: true,
    placeholder: '请选择角色',
    options: () => {
      return formRoleOptions.value;
    },
    eName: 'roleIds'
  },
  {
    type: 'select',
    value: '',
    label: '是否健康顾问',
    required: true,
    options: () => {
      return [
        { name: '是', id: true },
        { name: '否', id: false }
      ];
    },
    eName: 'isHealthDoctor'
  }
]);
let dialogForAssistantFormDatas = reactive([
  {
    type: 'select',
    value: '',
    label: '归属检测点',
    placeholder: '请选择归属检测点',
    options: () => {
      return checkPoints.value;
    },
    eName: 'checkPoints'
  },
  {
    type: 'input',
    value: '',
    label: '邮箱地址',
    placeholder: '请选择邮箱地址',
    eName: 'email'
  },
  {
    type: 'input',
    value: '',
    label: '当前职务',
    placeholder: '请选择当前职务',
    eName: 'currentPosition'
  },
  {
    type: 'input',
    value: '',
    label: '座机/分机',
    placeholder: '请选择座机/分机',
    eName: 'telephone'
  },
  {
    type: 'radio',
    value: '',
    label: '员工性别',
    options: () => {
      return [
        { value: '男', label: 1 },
        { value: '女', label: 2 }
      ];
    },
    eName: 'gender'
  },

  {
    type: 'input',
    maxlength: '15',
    value: '',
    label: '所属部门',
    placeholder: '请选择所属部门',
    eName: 'department'
  },
  {
    type: 'select',
    value: '',
    label: '学历',
    placeholder: '请输入学历',
    options: () => {
      return educationOptions;
    },
    eName: 'education'
  },
  {
    type: 'input',
    value: '',
    label: '工号',
    placeholder: '请输入工号',
    eName: 'jobNumber'
  },
  {
    type: 'input',
    value: '',
    label: '籍贯',
    placeholder: '请输入籍贯',
    eName: 'nativePlace'
  },
  {
    type: 'input',
    value: '',
    label: '毕业院校',
    placeholder: '请输入毕业院校',
    eName: 'almaMater'
  },
  {
    type: 'date',
    value: '',
    label: '创建时间',
    placeholder: '请输入创建时间',
    eName: 'graduationDate'
  },
  {
    type: 'input',
    value: '',
    label: '所学专业',
    placeholder: '请输入所学专业',
    eName: 'major'
  },
  {
    type: 'textarea',
    value: '',
    label: '备注',
    placeholder: '请输入备注',
    eName: 'notes'
  }
]);
/** 方法 */
// banner 数据
const getAdminBannerNum = async () => {
  let data = await getAdminBanner();
  let statisticsDatas = data.data;
  contentList[0].number = statisticsDatas.staffs;
  contentList[1].number = statisticsDatas.hqstaffs;
  contentList[2].number = statisticsDatas.orgStaffs;
};
// 组织下拉
const getOrgOptionsDatas = async () => {
  const data: any = await orgOptionsRequest({ containBase: true });
  orgIdDatas = data.data;
};
// 检测点下拉
let checkPoints = ref([]);
const getCheckPointsOptionsFun = async (val: any) => {
  if (val && val !== null) {
    checkPoints.value = [];
    const data: any = await getCheckPointsOptionsRequest({ name: '', orgId: val });
    checkPoints.value = data.data;
  } else {
    checkPoints.value = [];
  }
};
// 角色下拉
const getRoleOptions = async (id: any) => {
  if (id && id !== null) {
    const data: any = await roleOptionsRequest({ orgId: id });
    roleOptionsValue = data.data;
  } else {
    roleOptionsValue = [];
  }
};
// 数据筛选
const handleSearch = (searchFormParamsDatats: {}) => {
  Object.assign(searchFormParams, searchFormParamsDatats);
  getList();
};
// 筛选数据监听(归属组织)
watch(
  () => searchForm[1].value,
  (newVal, oldVal) => {
    searchForm[2].value = '';
    getRoleOptions(newVal);
  }
);
// 监听组织（form表单）
let formRoleOptions = ref([]);
watch(
  () => dialogForBaseFormDatas[2].value,
  (newVal, oldVal) => {
    // dialogForBaseFormDatas[4].value = '';
    getFormRoleOptions(newVal);
    getCheckPointsOptionsFun(newVal);
  },
  { deep: true }
);
const getFormRoleOptions = async (id: any) => {
  if (id && id !== null) {
    formRoleOptions.value = [];
    const data: any = await roleOptionsRequest({ orgId: id });
    formRoleOptions.value = data.data;
  } else {
    formRoleOptions.value = [];
  }
};
// 新建事件 start
/*清除表单值 */
const clearFormDatas = () => {
  dialogForBaseFormDatas.forEach((item) => {
    item.value = null;
  });
  dialogForAssistantFormDatas.forEach((item) => {
    item.value = '';
  });
};
const onCancel = () => {
  //取消
  clearFormDatas();
};
const chanFormValue = (formParamsDatats: {}) => {
  searchFormParams = formParamsDatats;
};
const onConfirm = async (data: any, type: any, oldVal: any) => {
  //确定
  if (type === 'edit') {
    //编辑
    let params = data;
    params['id'] = oldVal.id;
    const res: any = await adminUserEditRequest(params);
    if (res.code === 2000) {
      ElMessage.success(res.message);
      clearFormDatas();
      addOrUpdateRef.value.handleDialog(false);
      getList();
    }
  } else if (type === 'lzjc') {
    // await adminUserResignRequestFun(data);
  } else {
    //新增
    const res: any = await getadminUserSave(data);
    if (res.code === 2000) {
      ElMessage.success('保存成功');
      clearFormDatas();
      addOrUpdateRef.value.handleDialog(false);
      getList();
    }
  }
};
// 新建事件 end
const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
//设置弹出框内表单回显数据
const setDialogDefaultDatas = async (row: any, type: any) => {
  const data: any = await getInfoRequest({ id: row.id });
  const datas = data.data;
  dialogForBaseFormDatas.forEach((d) => {
    // if (d.eName === 'userStatusName') {
    //   if (datas[d.eName] === 1) {
    //     d.value = '在职启用';
    //   } else if (datas[d.eName] === 2) {
    //     d.value = '在职停用';
    //   } else {
    //     d.value = '离职';
    //   }
    //   return;
    // }
    roleOptionsValue = d.value = datas[d.eName];
  });
  dialogForAssistantFormDatas.forEach((d) => {
    d.value = datas[d.eName];
  });
  dialogDatas = {
    title: '查看',
    type: type,
    id: row.id,
    dialogForBaseFormDatas: dialogForBaseFormDatas,
    dialogForAssistantFormDatas: dialogForAssistantFormDatas
  };
  onAddOrUpdate(dialogDatas);
};
const onlizhi = (rowData: any) => {
  ElMessageBox.confirm('请确认是否已离职？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const data: any = await adminUserSetResignRequest({ resignId: rowData.id });
    if (data.code === 2000) {
      ElMessage.success('已确认');
      getList();
    } else {
      ElMessage.error(data?.message);
      return;
    }
    return;
  });
  // .catch(() => {
  //   ElMessage({
  //     type: 'info',
  //     message: '取消操作'
  //   });
  // });
};
/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams = {};
  searchForm = searchForm.map((item) => {
    if (item.value) {
      item.value = '';
    }
    return item;
  });
  getList();
};
const updateList = () => {
  getList();
  getAdminBannerNum();
  showDialog.value = false;
};
// 学历下拉
let educationOptions = reactive([]);
const showeducation = ref(true);
const geteducationOptions = async () => {
  showeducation.value = false;
  const data: any = await enumListRequest({ enumName: 'EducationEnum' });
  educationOptions = data.data;
  showeducation.value = true;
};
/* 更新停用/启用 */
const getEnableOrDisablDatas = async (param: object) => {
  const data: any = await adminUserUpdateStatusRequest(param);
};
onMounted(() => {
  if(!currentMenudatas.value) {
    return
  }
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value?.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value?.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
});

// 调用
getAdminBannerNum();
getOrgOptionsDatas();
getRoleOptions(null);
geteducationOptions();
</script>
<style scoped>
.packageCardcontainer {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;

  > .card {
    flex: 0 0 18%;
    min-width: 18%;
    margin-right: calc(9.99% / 4);
    margin-bottom: 10px;

    /* // 每行最后一个卡片 */
    &:nth-child(5n) {
      margin-right: 0;
    }

    /* // 最后一个卡片 */
    &:last-child {
      margin-right: auto;
    }
  }
}
</style>
